<template>
    <div class="layout-product">
        <ProductListHead class="layout-product-head" :query="query" @queryChange="queryChange($event)" />
        <div class="layout-product-content">
            <div class="layout-product-aside">
                <ProductLeftMenu :query="query" @queryChange="queryChange($event)" />
            </div>

            <div class="layout-product-warp">
                <!-- 加载中 -->
                <div class="product-warp-loading" v-show="loading">
                    <UxLoading2 :loading="true" />
                </div>

                <!-- 为空 -->
                <div class="product-warp-empty" v-show="!loading && productList.length == 0">
                    <img src="https://img.podpartner.com/static/images-20230202/listEmpty.png" alt="" />
                    <p v-if="query && query.type == 'collect'">No content found</p>
                    <p v-else>No content found</p>
                    <button @click="reset()">Browse products</button>
                </div>

                <!-- 有数据 -->
                <ProductListSort v-show="!loading && productList.length > 0" class="product-warp-list" :query="query" :list="productList" :total="productTotal" @queryChange="queryChange($event)" />
            </div>
        </div>
    </div>
</template>
<script>
// 从路由获取参数
let getQueryByRoute = (opt) => {
    let query = opt || {};
    let surface = (query.surface || "").split(",").filter((i) => i);
    let sizes = (query.sizes || "").split(",").filter((i) => i);
    let brands = (query.brands || "").split(",").filter((i) => i);

    return {
        classify: parseInt(query.classify) || 0, // 分类[]
        type: /new|collect/.test(query.type) ? query.type : "", // 类型[|new|collect]
        surface: surface, // 打印面
        sizes: sizes, // 打印面
        brands: brands, // 品牌
        sort: parseInt(query.sort) || 1, // 排序
        page: parseInt(query.page) || 1, // 当前分页
        limit: 9, // 分页每页条数
    };
};

// 获取数据
let getProductList = async (context, query) => {
    let list = [];
    let total = 0;

    if (query.type == "collect") {
        // 我的收藏，一次取全部，未做分页处理
        if (process.client) {
            let response = await context.$http("Product.getCollectList");

            let page = Math.max(query.page, 1);
            let start = (page - 1) * query.limit;
            let stop = page * query.limit;
            let data = response.data || [];

            total = data.length || 0;
            list = data.slice(start, stop);
        } else {
            // 不在客户端不管他
        }
    } else if (query.type == "new") {
        // 最新的
        // 取所有数据，取15天以内的时间
        let request = { page_size: 999, page_num: 1 };
        let response = await context.$http("Product.getList/", request);

        let time = parseInt(new Date().getTime() - 86400000 * 60) / 1000;
        let page = Math.max(query.page, 1);
        let start = (page - 1) * query.limit;
        let stop = page * query.limit;
        let data = (response.data || []).filter(i => i.created_at > time);

        // 排序
        data.sort((a, b) => b.created_at - a.created_at);
        list = data.slice(start, stop);
        total = data.length || 0;
    } else {
        // 正常
        let request = {};

        request.page_num = query.page || 1;
        request.page_size = query.limit;

        query.sort && (request.sort_status = query.sort);
        query.classify && (request.classify = query.classify);
        query.brands.length > 0 &&
            (request.brand_list = query.brands.join("|"));
        query.sizes.length > 0 && (request.size_list = query.sizes.join("|"));

        if (query.surface.length > 0) {
            let surface = query.surface.map((item) => {
                return item
                    .split("-")
                    .map((i) => i.replace(/\b\w/, (s) => s.toUpperCase()))
                    .join(" ");
            });
            request.printable_surface = surface.join("|");
        }

        let response = await context.$http("Product.getList/", request);
        list = response.data || [];
        total = response.total || 0;
    }

    if (process.client) {
        window.CACHE_PRODUCT_LIST = {
            query: JSON.stringify(query),
            list: list,
            total: total,
        };
    }

    let time = new Date().getTime() - 86400000 * 60;
    list.map(item => {
        item.isNew = parseInt((item.created_at + "0000000").substr(0, 13)) > time;
    })


    return {
        list: list,
        total: total,
    };
};

import { mapGetters } from "vuex";
import { PRODUCT } from "@/utils/SeoConfig";
export default {
    name: "ProductIndex",
    async asyncData (context) {
        let { app, route } = context;
        let query = getQueryByRoute(route.query);
        let productList = [];
        let productTotal = 0;
        let inited = false;

        if (process.client) {
            if (
                window.CACHE_PRODUCT_LIST &&
                window.CACHE_PRODUCT_LIST.query == JSON.stringify(query)
            ) {
                // 数据相同
                productList = window.CACHE_PRODUCT_LIST.list;
                productTotal = window.CACHE_PRODUCT_LIST.total;
            } else {
                inited = false;
            }
        } else {
            let response = await getProductList(app, query);
            productList = response.list;
            productTotal = response.total;
            inited = true;
        }

        return {
            loading: false,
            inited: inited,
            query: query,
            productList: productList,
            productTotal: productTotal,
        };
    },
    head ({ $store }) {
        return {
            title: PRODUCT.title,
            meta: [
                { name: "keywords", content: PRODUCT.keywords },
                { name: "description", content: PRODUCT.description },
            ],
        };
    },
    computed: {
        ...mapGetters({
            isLogin: "getIsLogin",
        }),
    },
    watch: {
        $route: {
            deep: true,
            handler (v, ov) {
                this.getData();
            },
        },
    },
    methods: {
        // 改变数据
        queryChange (event) {
            let option = event || {};
            let keys = Object.keys(this.query);
            let route = getQueryByRoute(this.$route.query);

            Object.keys(option).map((key) => {
                if (keys.indexOf(key) < 0) {
                    // 没有定义的字段不处理
                } else {
                    this.query[key] = option[key];
                    // 如果是排序方式切换，page重置到1
                    if (key == "sort") {
                        this.query.page = 1;
                    }
                }
            });

            if (JSON.stringify(route) == JSON.stringify(this.query)) {
                // 数据相同，不处理
            } else {
                let query = this.query;
                let form = {};

                query.type && (form.type = query.type);
                query.page > 1 && (form.page = query.page);
                query.sort > 1 && (form.sort = query.sort);
                query.classify && (form.classify = query.classify);
                query.brands.length > 0 &&
                    (form.brands = query.brands.join(","));
                query.sizes.length > 0 && (form.sizes = query.sizes.join(","));
                query.surface.length > 0 &&
                    (form.surface = query.surface.join(","));

                // 手动记录历史浏览记录
                const currentRoute = this.$router.currentRoute;

                const newRoute = {
                    path: currentRoute.path,
                    query: form,
                };

                window.history.pushState({}, '', this.$router.resolve(newRoute).href);

                this.$router
                    .replace({ path: this.$route.path, query: form })
                    .catch((err) => {
                        // console.log(err);
                    });
                window.scrollTo(0, 0);
            }
        },

        // 重置
        reset () {
            let query = JSON.parse(JSON.stringify(this.query));
            query.brands = [];
            query.sizes = [];
            query.surface = [];
            query.page = 1;
            query.sort = 1;
            query.page = 1;
            query.type = null;
            this.queryChange(query);
        },

        // 获取数据
        getData () {
            this.query = getQueryByRoute(this.$route.query);
            if (this.query.type == "collect" && !this.isLogin) {
                this.$emit("global:userLogin", (e) => {
                    getProductList(this, this.query).then((response) => {
                        this.productList = response.list;
                        this.productTotal = response.total;
                        this.loading = false;
                    });
                });
            } else if (
                window.CACHE_PRODUCT_LIST &&
                window.CACHE_PRODUCT_LIST.query == JSON.stringify(this.query)
            ) {
                // 数据相同
                this.productList = window.CACHE_PRODUCT_LIST.list;
                this.productTotal = window.CACHE_PRODUCT_LIST.total;
            } else {
                this.loading = true;
                getProductList(this, this.query).then((response) => {
                    this.productList = response.list;
                    this.productTotal = response.total;
                    this.loading = false;
                });
            }
        },
    },
    created () {
        if (!process.client) {
            // 服务端
        } else {
            // 第一次加载界面时
            window.CACHE_PRODUCT_LIST = {
                query: JSON.stringify(this.query),
                list: JSON.parse(JSON.stringify(this.productList)),
                total: this.productTotal,
            };
            if (this.productList.length == 0) {
                window.CACHE_PRODUCT_LIST.query = "";
                this.getData();
            }
        }
    },
};
</script>
<style lang="scss" scoped>
.layout-product {
    box-sizing: border-box;
    padding: 0 20px 0;
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    position: relative;
    display: flex;
    flex-direction: column;
}
.layout-product-content {
    flex: 1;
    display: flex;
    flex-direction: row;
}

.layout-product-head {
    padding: 40px 0;
}

.layout-product-aside {
    width: 200px;
}

.layout-product-warp {
    margin-left: 32px;
    flex: 1;
    position: relative;
}

.product-warp-loading {
    position: fixed;
    width: 100%;
    left: 50%;
    box-sizing: border-box;
    transform: translateX(-50%);
    max-width: 1200px;
    top: 78px;
    bottom: 0;
    z-index: 1;
    pointer-events: none;

    & > .loading {
        left: 200px;
        background: none;
    }

    // display: flex;
    // align-items: center;
    // justify-content: center;
    // height: 100%;
    // overflow: hidden;
}
.product-warp-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #aaaaaa;
    height: 100%;

    img {
        width: 264px;
        height: 180px;
        margin: 0 0 96px 0;
    }

    button {
        margin: 20px 0 0 0;
        width: 238px;
        height: 52px;
    }
}

@media (max-width: 960px) {
    .layout-product {
        padding: 0 14px;
    }
    .layout-product-aside {
        display: none;
    }
    .layout-product-head {
        padding: 28px 0 4px;
    }
    .layout-product-warp {
        margin-left: 0;
    }

    .product-warp-empty {
        color: #555;
        img {
            margin-bottom: 48px;
        }
        button {
            height: 40px;
            margin-top: 12px;
        }
    }
}
</style>
